package com.zr.domain.sp.tool.mq.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

@Component
public class RabbitTemplateAck {
    Logger logger = LoggerFactory.getLogger(RabbitTemplateAck.class);

    @Autowired
    RabbitTemplate rabbitTemplate;

    @PostConstruct
    public void init() {
        returnsCallback();
        confirmCallback();
    }

    /**
     * 消息没有路由到队列的时候会被调用
     */
    public void returnsCallback() {
        rabbitTemplate.setReturnsCallback(new RabbitTemplate.ReturnsCallback() {
            @Override
            public void returnedMessage(ReturnedMessage returnedMessage) {
                logger.info("消息主体 message:{}", returnedMessage.getMessage());
                logger.info("消息主体 code:{}", returnedMessage.getReplyCode());
                logger.info("描述:{}", returnedMessage.getReplyText());
                logger.info("消息使用的交换器 exchange : {}", returnedMessage.getExchange());
                logger.info("消息使用的路由键 routing : {}", returnedMessage.getRoutingKey());
            }

        });
    }

    /**
     * 消息没有路由到交换机的时候会被调用
     */
    public void confirmCallback() {
        rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
            @Override
            public void confirm(CorrelationData correlationData, boolean ack, String cause) {
                logger.info("消息唯一标识：{}", correlationData);
                logger.info("确认结果：{}", ack);
                logger.info("失败原因：{}", cause);
            }
        });
    }
}
